<template>
	<view class="px-2 py-4">
		<form-component :formFields="formFields" :formData="formData" :formRules="formRules" :fileLists="fileLists"
			:startUserSelectTasks="startUserSelectTasks" :startUserSelectAssignees="startUserSelectAssignees"
			:startUserSelectAssigneesFormRules="startUserSelectAssigneesFormRules" :detailId="detailId"
			:resubmit="resubmit" @submitForm="submitForm" @cancelForm="cancelForm" />

	</view>
</template>

<script setup lang="ts">
import {
	onLoad
} from "@dcloudio/uni-app";
import { ref, reactive, nextTick } from 'vue'
import { isEmpty } from '@/utils/is'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as DefinitionApi from '@/api/bpm/definition'
import { getAccessToken } from '@/utils/auth'
import { useApprovedTasksStore } from '@/store/modules/approvedTasksStore';
import { useUserStore } from '@/store/modules/user'
import { formatDate, formatPast2 } from '@/utils/formatTime'
import { LawContractReviewApi, LawContractReviewVO } from '@/api/legal/contractManager/groupcontract'
import { useMessage, useToast } from 'wot-design-uni'
import { getFileName, parseArrayField, buildFileList } from '@/utils/fileUtils'


const globalConfig = (getApp() as any).globalData.config;
const message = useMessage()
const toast = useToast()
const detailId = ref(null)
const resubmit = ref(0)
const headerObj = ref(
	{
		Authorization: 'Bearer ' + getAccessToken()
	}
)
// 指定审批人
const processDefineKey = 'Law_unitContractApproval' // 流程定义 Key
const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRef = ref() // 发起人选择审批人的表单 Ref
const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules
// 独立文件存储（按字段名存储）
const fileLists = ref<Record<string, any[]>>({
	eids: []
})

const formFields = ref<any[]>([
	{ type: 'input', prop: 'contractName', label: '合同名称', placeholder: '请输入合同名称' },
	{ type: 'input', prop: 'contractNumber', label: '合同编号', placeholder: '请输入合同编号' },
	{ type: 'input', prop: 'firstParty', label: '甲方', placeholder: '请输入甲方' },
	{ type: 'input', prop: 'secondParty', label: '乙方', placeholder: '请输入乙方' },
	{ type: 'input', prop: 'thirdParty', label: '丙方', placeholder: '请输入丙方' },
	{ type: 'input', prop: 'contractCategory', label: '合同类别', placeholder: '请输入合同类别' },
	{ type: 'input', prop: 'contractAmount', label: '合同金额', placeholder: '请输入合同金额' },
	{ type: 'input', prop: 'affiliatedEnterprise', label: '所属企业', placeholder: '请输入所属企业' },
	{ type: 'input', prop: 'contractorContact', label: '承办联系人', placeholder: '请输入承办联系人' },
	{ type: 'input', prop: 'contractorContactPhone', label: '承办联系人电话', placeholder: '请输入电话' },
	{
		type: 'radio',
		prop: 'accredit',
		label: '是否授权',
		placeholder: '请输入是否授权',
		options: [
			{
				value: 0,
				label: '是',
			},
			{
				value: 1,
				label: '否',
			}
		],
		optionLabel: 'label',
		optionValue: 'value',
		inline: true,
	},
	{ type: 'input', prop: 'nameOfAgent', label: '委托代理人姓名', placeholder: '请输入委托代理人姓名' },
	{ type: 'input', prop: 'remark', label: '备注', placeholder: '请输入备注' },
	{
		type: 'upload', prop: 'eids', label: '附件', placeholder: '请输入附件',
		action: globalConfig.uploadUrl,
		// limit: 1,
		accept: 'all',
		isMultipleArray: true,
		header: headerObj.value,
		targetMapping: {         // 字段映射配置
			fileUrl: 'eids',    // 接口返回ID -> formData.serverIds
			fileName: 'ename'     // 文件名 -> formData.fileName
		}
	},
])

const formData = ref<LawContractReviewVO>({
	id: undefined,
	contractName: undefined,
	contractNumber: undefined,
	firstParty: undefined,
	secondParty: undefined,
	contractCategory: undefined,
	contractAmount: undefined,
	affiliatedEnterprise: undefined,
	contractorContact: undefined,
	contractorContactPhone: undefined,
	accredit: undefined,
	nameOfAgent: undefined,
	unitResponsibleOpinion: undefined,
	unitResponsibleOpinionSignature: undefined,
	unitResponsibleOpinionTime: undefined,
	legalDeptHeadOpinion: undefined,
	legalDeptHeadSignature: undefined,
	legalDeptHeadSignTime: undefined,
	supervisorOpinion: undefined,
	supervisorSign: undefined,
	supervisorSignDate: undefined,
	generalManagerOpinion: undefined,
	generalManagerSign: undefined,
	generalManagerSignDate: undefined,
	chairmanOpinion: undefined,
	chairmanSign: undefined,
	chairmanSignDate: undefined,
	processInstanceId: undefined,
	status: undefined,
	remark: undefined,
} as any)
const formRules = reactive({
	contractName: [
		{
			required: true,
			message: '请输入合同名称',
			trigger: ['blur', 'change'],
		},
	],
	contractNumber: [
		{
			required: true,
			message: '请输入合同编号',
			trigger: ['blur', 'change'],
		},
	],
	firstParty: [
		{
			required: true,
			message: '请输入甲方',
			trigger: ['blur', 'change'],
		},
	],
	secondParty: [
		{
			required: true,
			message: '请输入乙方',
			trigger: ['blur', 'change'],
		},
	],
	
	contractCategory: [
		{
			required: true,
			message: '请输入合同类别',
			trigger: ['blur', 'change'],
		},
	],
	contractAmount: [
		{
			required: true,
			message: '请输入合同金额',
			trigger: ['blur', 'change'],
		},
	],
	affiliatedEnterprise: [
		{
			required: true,
			message: '请输入所属企业',
			trigger: ['blur', 'change'],
		},
	],
	contractorContact: [
		{
			required: true,
			message: '请输入承办联系人',
			trigger: ['blur', 'change'],
		},
	],
	contractorContactPhone: [
		{
			required: true,
			message: '请输入电话',
			trigger: ['blur', 'change'],
		},
		{
			pattern: /^1[3-9]\d{9}$|^(\+?\d{1,4}[-\s]?)?(\d{3,4}[-\s]?)?\d{7,8}$/
			,
			message: '请输入有效的电话号',
			trigger: ['blur', 'change'],
		},
	],
})


onLoad(async (options) => {
	const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
		undefined,
		processDefineKey
	)
	if (!processDefinitionDetail) {
		toast.error('流程模型未配置，请检查！')
		return
	}
	startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
	// 设置指定审批人
	if (startUserSelectTasks.value?.length > 0) {
		// 设置校验规则
		for (const userTask of startUserSelectTasks.value) {
			startUserSelectAssignees.value[userTask.id] = []
			startUserSelectAssigneesFormRules.value[userTask.id] = [
				{

					required: true,
					message: '请选择审批人',
					validator: (value: any) => {
						console.log("当前审批人值435435:", value); // 调试输出
						if (value && Array.isArray(value) && value.length > 0) {
							console.log('value.length', value.length);
							return Promise.resolve();
						} else {
							return Promise.reject('审批人不能为空');
						}
					},
					trigger: ['change']

				}
			]
		}
		console.log('startUserSelectAssignees.value', startUserSelectAssignees.value);
		console.log('startUserSelectAssigneesFormRules.value', startUserSelectAssigneesFormRules.value);
	}
	detailId.value = options?.id
	resubmit.value = options?.resubmit
	/** 获得详情 */
	if (detailId.value) { getDetailById() }
})

/** 获取页面详情 */
const getDetailById = async () => {
	try {
		const data = await LawContractReviewApi.getLawContractReview(Number(detailId.value))
		formData.value = data
		// 附件字段回显
		formData.value.eids = parseArrayField(data.eids);
		formData.value.ename = parseArrayField(data.ename);
		fileLists.value.eids = buildFileList(formData.value.eids, formData.value.ename) as any;

		console.log('formData.value', formData.value);
	} catch (error) {
		console.log('加载数据失败')
	}
}

/** 提交表单 */
const submitForm = async (payload: any) => {
	const { type, data } = payload
	console.log('data', data);

	try {
		if (type === 'update') {
			await LawContractReviewApi.updateLawContractReview(data)
			toast.success('编辑成功');
		} else {
			await LawContractReviewApi.createLawContractReview(data)
			toast.success('新增成功');
		}
		// 成功后跳转
		uni.navigateTo({ url: '/pagesPackage/Legal/contractManager/index' });
	} catch (error) {
		console.error('表单提交失败:', error);
		toast.error('提交失败，请稍后再试');
	}
}

/** 取消表单 */
const cancelForm = async () => {
	try {
		// 删除的二次确认
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示'  // 添加标题
		})
		uni.navigateTo({ url: '/pagesPackage/Legal/contractManager/index' });
		// 显示成功提示
		toast.success('取消成功')
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
</script>

<style scoped lang="scss">
.container {
	padding: 20px 5px;
}

.custom-shadow {
	width: 40%;
	border-radius: 5%;
}
</style>